package com.qianyucc.blog.global;

import com.qianyucc.blog.exception.*;
import com.qianyucc.blog.model.enums.*;
import com.qianyucc.blog.model.vo.*;
import lombok.extern.slf4j.*;
import org.springframework.http.*;
import org.springframework.validation.*;
import org.springframework.web.bind.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.*;

import javax.servlet.http.*;

/**
 * @author lijing
 * @date 2019-10-12 10:37
 * @description 全局异常处理
 */
@ControllerAdvice
@Slf4j
class ApiExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = BaseException.class)
    public ResponseEntity<ResultVO> handleApiException(Exception exception, HttpServletResponse response) {
        BaseException baseException = (BaseException) exception;
        if (baseException instanceof TokenExpiredException) {
            log.warn("message:{}", exception.getMessage());
            response.setStatus(403);
        } else {
            log.error("message:{}", exception.getMessage());
            response.setStatus(500);
        }
        ResultVO resultVO = ResultVO.error(baseException);
        return new ResponseEntity<>(resultVO, HttpStatus.valueOf(response.getStatus()));
    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseBody
    public ResponseEntity<ResultVO> handleNoHandlerFoundException(Exception exception) {
        log.error("message:{}", exception.getMessage());
        ResultVO resultVO = ResultVO.error(exception.getMessage(), RespCode.RESOURCES_NOT_FOUND);
        return new ResponseEntity<>(resultVO, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<ResultVO> handleMethodArgumentNotValidException(Exception exception, HttpServletResponse response) {
        String message = getMessage((MethodArgumentNotValidException) exception);
        log.error("message:{}", message);
        ResultVO resultVO = ResultVO.error(message, RespCode.MISSING_PARAMETERS);
        return new ResponseEntity<>(resultVO, HttpStatus.valueOf(response.getStatus()));
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<ResultVO> exception(Exception exception) {
        exception.printStackTrace();
        log.error("message:{}", exception.getMessage());
        //未知异常
        ResultVO resultVO = ResultVO.error(exception.getMessage());
        return new ResponseEntity<>(resultVO, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 结合BeanValid，格式化异常信息
     *
     * @param ex
     * @return
     */
    private String getMessage(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder();
        for (FieldError error : bindingResult.getFieldErrors()) {
            String field = error.getField();
            Object value = error.getRejectedValue();
            String msg = error.getDefaultMessage();
            String message = String.format("错误字段：%s，错误值：%s，原因：%s；", field, value, msg);
            sb.append(message);
        }
        return sb.toString();
    }
}
